﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sands.DataAccess;
using SAWeb.Model;
using SAWeb.Service;
using Sands.Common;
using Sands.Web;

namespace SAWeb.Web.Admin
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Context.GetCookie("webcmsadminname").IsNotNull())
                {
                    userName.Text = Context.GetCookie("webcmsadminname");
                    AutoGet.Checked = true;
                }
            }
        }

        protected void lbtnLogin_Click(object sender, EventArgs e)
        {
            "登陆".InfoAction(() =>
            {
                if (Request.Cookies["AuthCode"].IsNull())
                    throw new SandsException("验证码过期，请点击验证码刷新");
                if (Request.Cookies["AuthCode"].Value.ToString().ToLower() != txtAuthCode.Text.ToLower())
                    throw new SandsException("验证码错误，请重新输入");
                string uname = userName.Text.Trim();
                string upwd = pwd.Text.Trim();
                using (AdminService service = new AdminService())
                {
                    WhereClip where = Model.Admin.F.AdminName == uname & Model.Admin.F.Pwd == upwd;
                    Model.Admin model = service.GetModel(where);
                    if (model.IsNull())
                    {
                        throw new SandsException("用户名或密码错误");
                    }
                    else
                    {
                        SessionHelper<Model.Admin>.Add(model);
                        Response.Redirect("/Admin/index.aspx");
                    }
                }
            });
        }

        protected void AutoGet_CheckedChanged(object sender, EventArgs e)
        {
            if (AutoGet.Checked == true)
                CookiesHelper.WriteCookie(Context, "webcmsadminname", userName.Text, 7);
            else
                CookiesHelper.RemoveCookies(Context, "webcmsadminname");
        }
    }
}